package com.ax.framework.jfinal.engine;

import cn.hutool.core.util.ReflectUtil
import com.jfinal.plugin.activerecord.ActiveRecordException
import com.jfinal.plugin.activerecord.SqlPara
import com.jfinal.template.Directive
import com.jfinal.template.Env
import com.jfinal.template.io.Writer
import com.jfinal.template.stat.Scope

/**
 *
 *
 * @author 张天笑
 * @time 2018/11/12 0:08
 *
 */
class PDirective : Directive() {

    override fun exec(env: Env, scope: Scope, writer: Writer) {
        val sb = ReflectUtil.getFieldValue(this.stat, "content") as StringBuilder
        //按回车换行解析出的每一行字符串
        val fragments = sb.split("\n").filter { it.isNotEmpty() }
        //不为空白字符串, 不为空串, 且包含问号
        val para_framments = fragments.filter { it.isNotBlank() && it.isNotEmpty() && it.contains("?") }

        //传入指令的参数列表
        val directory_params = exprList.exprArray
        //带有问号的字符串片段长度 与参数列表长度不同
        if (para_framments.size != directory_params.size) {
            throw ActiveRecordException("带有问号的字符串片段长度 与参数列表长度不同")
        }
        val sqlPara = scope.get("_SQL_PARA_") as SqlPara
        var i = 0
        fragments.forEach {
            if (it.contains("?")) {
                val name = directory_params[i++]
                val value = name.eval(scope)
                if (value != null) {
                    sqlPara.addPara(value)
                    write(writer, it)
                    write(writer, "\n")
                }
            }
        }
        //  stat.exec(env, scope, writer)
    }


    override fun hasEnd() = true

}





